package com.jt.auth.service;

/**
 * @author 金帮嘉诚 @date 2021-08-26 星期四 15:52
 */

import com.jt.auth.feign.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录时 用户信息的获取和封装会在此对象进行实现
 * 在页面上点击登录按钮时 会调用这个对象的
 * 页面上输入的用户名会传给这个方法的参数
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 2021-08-31 17:34:37
     * 在写了feign后 添加下面这句
     */
    @Autowired
    private RemoteUserService remoteUserService;

    //UserDetails用户封装用户信息(认证和权限信息)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名查询用户信息(用户名,,..)
//        String encodePassword =
//                passwordEncoder.encode("123456");

        com.jt.auth.pojo.User user = remoteUserService.selectUserByUsername(username);
        //2.封装
        //应该有一步检查用户状态 禁用了就不能登录
        List<String> permissions = remoteUserService.listPermissions(user.getId());
        List<GrantedAuthority> authorityList =
                //这个参数是一个数组类型,所以要转换为String数组
//                AuthorityUtils.createAuthorityList("sys:res:create", "sys:res:retrieve");
                AuthorityUtils.createAuthorityList(
                        permissions.toArray(new String[]{}));
//        return new User(username, encodePassword, authorityList);
        return new User(username, user.getPassword(), authorityList);
    }
}
